import { useState, useEffect } from 'react';
import axios from 'axios';

// 药品数据接口
export interface DrugData {
  id?: number;
  restorativesid?: number;
  restorativesimage: string;
  restorativesname: string;
  restorativesstate: string;
  restorativesprice: number;
}

// 药品状态分类映射
export const drugStateCategories = {
  '2': ['男性健康', '男科用药', '持久', '内分泌类', '生发', '泌尿系统', '早泄', '男性'],
  '3': ['妇科', '女性', '抗菌消炎', '痛经', '炎症', '阴道', 'HPV疫苗', '妇科用药'],
  '4': ['感冒', '感冒发热', '止痛', '腹泻', '呼吸系统类', '清热解毒', '肠胃药', '常备药'],
  '5': ['风湿骨痛', '骨痛', '关节', '骨骼', '腰椎', '颈椎', '关节炎', '风湿病'],
  '6': ['皮肤用药', '湿疹', '皮炎', '痤疮', '痘痘', '美白', '保湿', '五官用药'],
  '7': ['维生素', '营养', '保健', '免疫', '补全维生素', '维矿物质', '滋补调养', '营养保健']
};

// Tab 配置接口
export interface TabConfig {
  key: string;
  label: string;
  maxItems?: number;
}

// 默认 Tab 配置
export const defaultTabConfigs: TabConfig[] = [
  { key: '1', label: '精选热销', maxItems: 12 },
  { key: '2', label: '男人健康', maxItems: 10 },
  { key: '3', label: '女性养护', maxItems: 10 },
  { key: '4', label: '家庭常备', maxItems: 10 },
  { key: '5', label: '风湿骨痛', maxItems: 10 },
  { key: '6', label: '皮肤用药', maxItems: 10 },
  { key: '7', label: '营养保健', maxItems: 10 }
];

// 自定义 Hook：药品分类管理
export const useDrugCategories = () => {
  const [drugList, setDrugList] = useState<DrugData[]>([]);
  const [activeTab, setActiveTab] = useState('1');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取药品数据
  const fetchDrugs = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await axios.get('/api/restorative/list', {
        params: {
          page: 1,
          pageSize: 100,
          limit: 100,
          size: 100
        }
      });
      console.log('药品数据响应:', res.data.data);
      setDrugList(res.data.data);
    } catch (err: any) {
      console.error('获取药品数据失败:', err);
      setError(err.message || '获取药品数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 根据分类过滤药品
  const getFilteredDrugs = (tabKey: string, maxItems?: number): DrugData[] => {
    if (tabKey === '1') {
      // 精选热销显示所有药品
      return drugList.slice(0, maxItems || 12);
    }
    
    const stateKeywords = drugStateCategories[tabKey as keyof typeof drugStateCategories] || [];
    const filtered = drugList.filter(drug => 
      stateKeywords.some(keyword => 
        drug.restorativesstate.toLowerCase().includes(keyword.toLowerCase())
      )
    );
    
    return filtered.slice(0, maxItems || 10);
  };

  // 获取所有分类的药品数据
  const getAllCategoryDrugs = (tabConfigs: TabConfig[] = defaultTabConfigs) => {
    return tabConfigs.reduce((acc, config) => {
      acc[config.key] = getFilteredDrugs(config.key, config.maxItems);
      return acc;
    }, {} as Record<string, DrugData[]>);
  };

  // 切换 Tab
  const changeTab = (key: string) => {
    setActiveTab(key);
  };

  // 初始化数据
  useEffect(() => {
    fetchDrugs();
  }, []);

  return {
    drugList,
    activeTab,
    loading,
    error,
    getFilteredDrugs,
    getAllCategoryDrugs,
    changeTab,
    refetch: fetchDrugs
  };
};
